package topcbl.taxi;

import java.util.ArrayList;
import java.util.List;

import topcbl.adapter.AutoCompleteTextAdapter;
import topcbl.adapter.NavigationDrawerAdapter;
import topcbl.database.TaxiDatabase;
import topcbl.net.Bind2Service;
import topcbl.net.TaxiService;
import topcbl.util.GPSTracker;
import android.app.ActionBar;
import android.content.Context;
import android.content.res.Configuration;
import android.location.Address;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends FragmentActivity {
	// View
	ImageView btnFavorite;
	AutoCompleteTextView autoCompleteText;
	AutoCompleteTextAdapter completeTextAdapter;
	SuggestPlacesTask mSuggestThread;
	ActionBar actionBar;

	// navigation drawer
	DrawerLayout mDrawerLayout;
	ListView mDrawerList;
	NavigationDrawerAdapter navigationAdapter;
	String[] navigationData;
	ActionBarDrawerToggle mDrawerToggle;
	FragmentManager fragmentManager;
	ArrayList<Fragment> listFragment;
	int curFragment = 2;

	// User XMPP
	public static Bind2Service mBindService;
	private TaxiService mService;
	// Database
	public static TaxiDatabase myDatabase;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setContentView(R.layout.activity_main);
		fragmentManager = getSupportFragmentManager();
		myDatabase = new TaxiDatabase(MainActivity.this);
		mService = mBindService.getService();
		createListFragment();
		createNavigationDrawer();
		createActionBar();
		if (savedInstanceState == null) {
			fragmentManager
					.beginTransaction()
					.replace(R.id.content_frame,
							listFragment.get(curFragment - 1)).commit();
		}
	}

	private void createListFragment() {
		ArrayList<Fragment> listFrag = new ArrayList<Fragment>();
		listFrag.add(new SignInFragment());
		listFrag.add(new MapFragment());
		listFrag.add(new FavoriteFragment());
		listFrag.add(new HistoryFragment());
		listFrag.add(new DriverFragment());
		listFragment = listFrag;
	}

	private void changeFragment(int position) {
		// only show action bar in find car tab
		if (position == 2)
			actionBar.setDisplayShowCustomEnabled(true);
		else
			actionBar.setDisplayShowCustomEnabled(false);
		// sign out if signed in
		if (position == 1 && mService.isLogin()) {
			navigationData[0] = getResources().getStringArray(
					R.array.navigation_item)[0];
			navigationData[1] = getString(R.string.navigation_item_change1);
			navigationAdapter.notifyDataSetChanged();
			mService.logout();
			actionBar.setDisplayShowCustomEnabled(true);
		}
		// change fragment
		else if (position != curFragment) {
			curFragment = position;
			fragmentManager
					.beginTransaction()
					.replace(R.id.content_frame,
							listFragment.get(curFragment - 1)).commit();
		}
	}

	private void createNavigationDrawer() {
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		navigationData = getResources().getStringArray(R.array.navigation_item);
		if (mService.isLogin()) { // check sign in
			navigationData[1] = getString(R.string.navigation_item_change2);
			navigationData[0] = mService.getUser();
		}
		navigationAdapter = new NavigationDrawerAdapter(MainActivity.this,
				R.layout.row_navigation_drawer, navigationData);
		mDrawerList.setAdapter(navigationAdapter);
		mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				if (position > 0) {
					changeFragment(position);
					mDrawerList.setItemChecked(position, true);
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			}
		});
		mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,
				mDrawerLayout, R.drawable.ic_action_settings,
				R.drawable.ic_action_settings, R.drawable.ic_action_settings) {
			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
			}

			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
	}

	private void createActionBar() {
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayShowCustomEnabled(true);
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflator.inflate(R.layout.action_bar, null);
		actionBar.setCustomView(v);
		autoCompleteText = (AutoCompleteTextView) v
				.findViewById(R.id.autoCompleteTextView1);
		completeTextAdapter = new AutoCompleteTextAdapter(MainActivity.this,
				R.layout.row_autocompletetext, new ArrayList<String>());
		autoCompleteText.setAdapter(completeTextAdapter);
		autoCompleteText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (start != 0) { // just suggest text when user type
					mSuggestThread = new SuggestPlacesTask();
					mSuggestThread.execute(s.toString());
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		View deleteTextBtn = (View) v.findViewById(R.id.imageView1);
		deleteTextBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				autoCompleteText.setText("");
			}
		});
		btnFavorite = (ImageView) v.findViewById(R.id.action_bar_btn_favorite);
		btnFavorite.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				MapFragment mapFragment = (MapFragment) listFragment.get(1);
				double lat = mapFragment.gpsTracker.getLatitude();
				double lng = mapFragment.gpsTracker.getLongitude();
				new AddFavoriteDialog(MainActivity.this, lat, lng).show();
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume() {
		super.onResume();
		((MapFragment) listFragment.get(1)).gpsTracker.getLocation();
	}

	private class SuggestPlacesTask extends
			AsyncTask<String, Void, ArrayList<String>> {

		@Override
		// three dots is java for an array of strings
		protected ArrayList<String> doInBackground(String... s) {
			List<Address> listAddress = GPSTracker.getCoordinateFromAddress(
					s[0], MainActivity.this);
			ArrayList<String> addresses = new ArrayList<String>();
			if (listAddress != null) {
				for (int i = 0; i < listAddress.size(); i++) {
					addresses
							.add(((listAddress.get(i).getAddressLine(0) == null) ? ""
									: listAddress.get(i).getAddressLine(0))
									+ ", "
									+ ((listAddress.get(i).getAddressLine(1) == null) ? ""
											: listAddress.get(i)
													.getAddressLine(1))
									+ ", "
									+ ((listAddress.get(i).getAddressLine(2) == null) ? ""
											: listAddress.get(i)
													.getAddressLine(2)));
				}
			}
			return addresses;
		}

		// then our post
		@Override
		protected void onPostExecute(ArrayList<String> result) {
			if (result != null) {
				completeTextAdapter = new AutoCompleteTextAdapter(
						MainActivity.this, R.layout.row_autocompletetext,
						result);
				autoCompleteText.setAdapter(completeTextAdapter);
				completeTextAdapter.notifyDataSetChanged();
			}
		}
	}

	public void setAddress(String address) {
		autoCompleteText.setText(address);
	}

	public void moveMap() {
		MapFragment mapFragment = (MapFragment) listFragment.get(1);
		if (mapFragment.gpsTracker != null) {
			List<Address> list = GPSTracker.getCoordinateFromAddress(
					autoCompleteText.getText() + "", MainActivity.this);
			if (list.size() > 0) {
				mapFragment.gpsTracker.setLocation(new LatLng(list.get(0)
						.getLatitude(), list.get(0).getLongitude()));
				mapFragment.marker = mapFragment.putMarkerOnMap(list.get(0)
						.getLatitude(), list.get(0).getLongitude(),
						R.drawable.user_pin);
				mapFragment.marker.showInfoWindow();
				mapFragment.map.animateCamera(CameraUpdateFactory
						.newLatLngZoom(new LatLng(list.get(0).getLatitude(),
								list.get(0).getLongitude()), 16));
			}
		}
	}
}
